using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Nirvana.AB
{
    public enum ExportAssetType
    {
        /// <summary>
        /// 普通资源，被根引用依赖
        /// </summary>
        Asset = 1,
        /// <summary>
        /// 根
        /// </summary>
        Root = 2,
    }
    
    public class AssetTarget
    {
        /// <summary>
        /// Unity内置资源的地址
        /// </summary>
        public const string builtinResourcesPath = "Resources/unity_builtin_extra";
        /// <summary>
        /// 相对于Assets的文件夹目录
        /// </summary>
        public string assetPath;
        /// <summary>
        /// 资源导出类型
        /// </summary>
        public ExportAssetType exportAssetType = ExportAssetType.Asset;
        /// <summary>
        /// 父依赖
        /// </summary>
        public HashSet<AssetTarget> dependParentSet = new HashSet<AssetTarget>();
        /// <summary>
        /// 子依赖
        /// </summary>
        public HashSet<AssetTarget> dependChildSet = new HashSet<AssetTarget>();
        /// <summary>
        /// 使用流加载
        /// </summary>
        public bool useStreamingLoad = false;
        /// <summary>
        /// 是否已分析过依赖
        /// </summary>
        private bool _isAnalyzed = false;
        /// <summary>
        /// 是否已merge
        /// </summary>
        private bool _isMerge = false;

        public AssetTarget(string assetPath)
        {
            this.assetPath = assetPath;
        }

        /// <summary>
        /// 分析引用依赖关系
        /// </summary>
        public void Analyze()
        {
            if (_isAnalyzed) return;
            _isAnalyzed = true;

            var depends = AssetDatabase.GetDependencies(assetPath, true);
            foreach (var depend in depends)
            {
                var extension = Path.GetExtension(depend);
                if (extension == ".meta" || extension == ".DS_Store" || extension == ".cs") continue;
                var target = AssetBundleUtils.Load(depend);
                if (target != null)
                {
                    dependChildSet.Add(target);
                    target.dependParentSet.Add(this);
                }
            }
        }

        /// <summary>
        /// 合并信息。如果子依赖用流加载，则根也用流加载
        /// </summary>
        public void Merge()
        {
            if (_isMerge) return;
            _isMerge = true;

            foreach (var unused in dependChildSet.Where(assetTarget => assetTarget.useStreamingLoad))
            {
                useStreamingLoad = true;
                break;
            }
        }
    }
}
